package com.hefan.api.controller.oms;

import com.alibaba.fastjson.JSONObject;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.google.common.collect.Maps;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.oms.RechargeLocalService;
import com.hefan.common.util.HttpUtils;
import com.hefan.oms.bean.RechargeCodePayVo;
import com.hefan.user.bean.WebUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

//import cn.saga.model.WebUser;
//import cn.saga.service.UserService;

@Controller
@RequestMapping("/")
public class RechargeCodeController {

	@Resource
	private RechargeLocalService rechargeLocalService;
	@Resource
	private UserLocalService userService;

	@RequestMapping(value = "v1/pay/rechargeCodePay" ,method= RequestMethod.GET)
	@ResponseBody
	public ResultBean rechargeCodePay(HttpServletRequest request) {
		RechargeCodePayVo rechargeCodePayVo = HttpUtils.initParam(request,RechargeCodePayVo.class);
		if(rechargeCodePayVo == null || StringUtils.isBlank(rechargeCodePayVo.getUserId()) || StringUtils.isBlank(rechargeCodePayVo.getRechargeCode())) {
			return new ResultBean(ResultCode.ParamException.get_code(), null);
		}
		WebUser webUser = userService.getWebUserByUserId(rechargeCodePayVo.getUserId());
		if(webUser == null) {
			return new ResultBean(ResultCode.RechangeCodePayErr1.get_code(),ResultCode.RechangeCodePayErr1.getMsg());
		}
		//验证充值码是否可用
		ResultBean checkResult =  rechargeLocalService.findValidRechargeInfoByCode(rechargeCodePayVo.getRechargeCode(),webUser.getUserId());
		if (checkResult.getCode() != ResultCode.SUCCESS.get_code()) {
			return  checkResult;
		}
		Map rechargeMap = (Map)checkResult.getData();
		Map userMap = new HashMap<>();
		userMap.put("userId",webUser.getUserId());
		userMap.put("balance",webUser.getBalance());
		userMap.put("nickName",webUser.getNickName());

		//充值码充值操作并返回所得饭票数
		Integer payFp = 0;
		try {
			payFp = rechargeLocalService.rechargeCodePayOpreate(userMap, rechargeMap, rechargeCodePayVo.getPaySource());
		}catch (Exception e){
			e.printStackTrace();
			return  new ResultBean(ResultCode.RechangeCodePayErr1.get_code(), "充值异常");
		}
		if(payFp == null) {
			return new ResultBean(ResultCode.RechangeCodePayErr1.get_code(), "充值失败");
		}
		//2016.11.22 add by 王超接口返回 当前总的余额和本次充值余额
		Map<String, Object> map = Maps.newHashMap();
		map.put("balance",webUser.getBalance()+payFp);
		map.put("change",payFp);

		return new ResultBean(ResultCode.SUCCESS.get_code(), ResultCode.SUCCESS.getMsg(), JSONObject.toJSON(map));

	}
}
